<template>
  <a-form
    :model="formState"
    name="basic"
    :label-col="{ span: 8 }"
    :wrapper-col="{ span: 16 }"
    autocomplete="off"
    @finish="onFinish"
    @finishFailed="onFinishFailed"
  >
    <a-form-item
      label="姓名"
      name="username"
      :rules="[{ required: true, message: '必须添加姓名!' }]"
    >
      <a-input v-model:value="formState.username" />
    </a-form-item>

    <a-form-item
      label="性别"
      name="sex"
    >
      <a-select
        ref="select"
        v-model:value="formState.sex"
        style="width: 120px"
      >
        <a-select-option value="男">男</a-select-option>
        <a-select-option value="女">女</a-select-option>
      </a-select>
    </a-form-item>

    <a-form-item
      label="年龄"
      name="age"
    >
    <a-input-number v-model:value="formState.age" />
    </a-form-item>


    <a-form-item :wrapper-col="{ offset: 8, span: 16 }">
      <a-button type="primary" @click="onFinish">{{formState.id?'更新':'添加'}}</a-button>
    </a-form-item>
  </a-form>
</template>
<script lang="ts" setup>
import { reactive,onMounted } from 'vue';
import axios from 'axios';
import { message } from 'ant-design-vue';
import { useRouter } from 'vue-router';

interface FormState {
  username: string;
  sex: string;
  age: number;
  id: number;

}

const formState = reactive<FormState>({
  username: '',
  sex: '',
  age: 1,
  id: 0,
});

onMounted(() => {
  let str = history.state.params
  if(str){
    let person = JSON.parse(str)
    Object.assign(formState,person)
    /* formState.username = person.username
    formState.sex = person.sex
    formState.age = person.age */
  }
})

const router = useRouter()

const onFinish = () => {
  axios.put('/api/update',formState).then(()=>{
    message.success('更新成功')
    router.push('/')
  })
};

const onFinishFailed = (errorInfo: any) => {
  console.log('Failed:', errorInfo);
};
</script>

